package com.symaster.alixanimation;

import com.alibaba.fastjson.JSONObject;
import com.symaster.alixanimation.util.CurveUtil;
import com.symaster.common.geom.entity.LineSegment;

import java.util.ArrayList;
import java.util.List;

public class Curve {
    private List<CurvePoint> curvePoints;
    private List<LineSegment> lineSegments;

    // 均衡
    public static final Curve TYPE_BALANCED = Curve.ofJson("{\"curvePoints\":[{\"x\":0.0,\"y\":1.0},{\"x\":0.25,\"y\":0.75},{\"x\":0.5,\"y\":0.5},{\"x\":0.75,\"y\":0.25},{\"x\":1.0,\"y\":0.0}]}");
    // 从快到慢
    public static final Curve TYPE_FAST_TO_SLOW = Curve.ofJson("{\"curvePoints\":[{\"x\":0.0,\"y\":1.0},{\"x\":0.25,\"y\":0.29},{\"x\":0.44,\"y\":0.13},{\"x\":0.72,\"y\":0.05},{\"x\":1.0,\"y\":0.0}]}");
    // 快 -> 慢 -> 快
    public static final Curve TYPE_FAST_TO_SLOW_TO_FAST = Curve.ofJson("{\"curvePoints\":[{\"x\":0.0,\"y\":1.0},{\"x\":0.1,\"y\":0.55},{\"x\":0.5,\"y\":0.5},{\"x\":0.9,\"y\":0.45},{\"x\":1.0,\"y\":0.0}]}");

    public Curve() {
    }

    public Curve(List<CurvePoint> curvePoints) {
        this.curvePoints = curvePoints;
        reloadLineSegment();
    }

    public static Curve ofJson(String jsonStr) {
        Curve curve = JSONObject.parseObject(jsonStr, Curve.class);
        curve.reloadLineSegment();
        return curve;
    }

    public List<CurvePoint> getCurvePoints() {
        return curvePoints;
    }

    public void setCurvePoints(List<CurvePoint> curvePoints) {
        this.curvePoints = curvePoints;
        reloadLineSegment();
    }

    public void reloadLineSegment() {
        if (curvePoints == null) {
            throw new NullPointerException();
        }
        this.lineSegments = CurveUtil.getBezierLines(curvePoints.toArray(new CurvePoint[0]));
    }

    public void initLineSegment() {
        if (lineSegments == null) {
            reloadLineSegment();
        }
    }

    public List<LineSegment> toLineSegments() {
        if (lineSegments == null) {
            throw new NullPointerException();
        }
        return new ArrayList<>(lineSegments);
    }

}
